package com.atguigu.gmall.oms.listener;

import com.atguigu.gmall.oms.entity.OrderEntity;
import com.atguigu.gmall.oms.service.OrderService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class OrderMqListener {
    @Autowired
    OrderService orderService;
    @Autowired
    RabbitTemplate rabbitTemplate;

    //监听支付成功消息：更新订单支付状态
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue("order-pay-queue"),
            exchange = @Exchange(value = "order_exchange" , type = ExchangeTypes.TOPIC,
                        ignoreDeclarationExceptions = "true"),
            key = "order.pay.success"
    ))
    public void orderpaySuccessListener(Message message , Channel channel , String orderToken) throws IOException {
        try {
            //更新订单的支付状态
            boolean update = orderService.update(new LambdaUpdateWrapper<OrderEntity>().eq(OrderEntity::getOrderSn, orderToken)
                    .set(OrderEntity::getStatus, 1));
            if(update){
                //订单状态更新成功: 更新订单的库存
                rabbitTemplate.convertAndSend("order_exchange","order.submit.success", orderToken);
            }
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            e.printStackTrace();
            if(message.getMessageProperties().isRedelivered()){
                channel.basicReject(message.getMessageProperties().getDeliveryTag(),false);
            }else{
                channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
            }
        }
    }

    /*
    队列监听器创建方式有两种：
        1、配置类通过@Bean标注方法返回 QUEUE Exchange对象。。。
        2、RabbitListener注解中通过@Queue 或者 @Exchange
     */
    @RabbitListener(queues = {"order_delay_queue"})
    public void orderCloseListener(Message message, Channel channel,String orderToken) throws IOException {
        try {
            //关单：根据orderToken查询订单 ，如果订单的状态是 待支付 修改订单为关单状态
            OrderEntity orderEntity = orderService.getOne(new LambdaQueryWrapper<OrderEntity>()
                    .eq(OrderEntity::getOrderSn, orderToken));
            if(orderEntity!=null && orderEntity.getStatus()==0){
                boolean b = orderService.update(new LambdaUpdateWrapper<OrderEntity>()
                        .eq(OrderEntity::getId, orderEntity.getId())
                        .set(OrderEntity::getStatus, 4));
                if(b){//关单成功：释放库存
                    //如果关单成功：释放库存
                    rabbitTemplate.convertAndSend("order_exchange","stock.unlock",orderToken);
                }
            }
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            e.printStackTrace();
            if(message.getMessageProperties().isRedelivered()){
                channel.basicReject(message.getMessageProperties().getDeliveryTag(),false);
            }else{
                channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
            }
        }
    }
}
